﻿   var fieldList = [];
   var sFList = [];
   var lastRow = 0;
  

  function FieldInfo(){
	 this.name = "";
	 this.code = "";
	 this.subFieldList = [];

	 this.setName = function(newName){
		this.name = newName;
	 }

	 this.getName = function(){
		return this.name;
	 }

	 this.setCode = function(newCode){
		this.code = newCode;
	 }

	 this.getCode = function(){
		return this.code;
	 }

   
     this.addSubFieldValue = function(subFieldValue){
         this.subFieldList[this.subFieldList.length] = new Array();
         this.subFieldList[this.subFieldList.length - 1] = subFieldValue;
     }
        
   }
   
   
  function SubFieldInfo(){
	 this.name = "";
	 this.code = "";
	 this.compareValueType = "";
	 this.valueList = [];
	 this.operatorList = [];
	 this.tableName = "";
	 this.columnName = "";
	 
	 this.setName = function(newName){
		this.name = newName;
	 }

	 this.getName = function(){
		return this.name;
	 }

	 this.setCode = function(newCode){
		this.code = newCode;
	 }

	 this.getCode = function(){
		return this.code;
	 }

	 this.setCompareValueType = function(compareValueType){
		this.compareValueType = compareValueType;
	 }

	 this.getCompareValueType = function(){
		return this.compareValueType;
	 }
     
    this.setTableName = function(newName){
		this.tableName = newName;
	}

	this.getTableName = function(){
		return this.tableName;
	}

	this.setColumnName = function(columnName){
		this.columnName = columnName;
	}

	this.getColumnName = function(){
		return this.columnName;
	}

    
     this.addOperateOption = function(optionValue,optionLable){
         this.operatorList[this.operatorList.length] = new Array();
         this.operatorList[this.operatorList.length - 1][0] = optionValue;
         this.operatorList[this.operatorList.length - 1][1] = optionLable;
     }
        
   
	 this.addValueOption = function(optionValue,optionLable){
     this.valueList[this.valueList.length] = new Array();
     this.valueList[this.valueList.length - 1][0] = optionValue;
	 this.valueList[this.valueList.length - 1][1] = optionLable;
	 }
	 
   }

  
   function fillValueList(selObjName,valueList){
	  var optionObj = null;
	 
	  var selObj = document.getElementById(selObjName);
	
	  while(length!=0){
	     var length=0;
	     if(selObj.options !=null){
	         length=selObj.options.length;
	     }
	    
         for(var i=0;i<length;i++)
             selObj.options.remove(i);
         length=length/2;
      }
     
	  for(var count= 0;count<valueList.length;count++){
		  optionObj = document.createElement("option");
	  	  optionObj.text = valueList[count][0];	
		  optionObj.value = valueList[count][1];
		  selObj.add(optionObj);
	  }		
   }

 function fillSymbolOption(firstSelObjName,selObjName,selectedIndex,rowId,rowNum){
     //alert("fillSymbolOption:firstSelObjName="+firstSelObjName+",selObjName="+selObjName+",selectedIndex="+selectedIndex+",rowId="+rowId+",rowNum="+rowNum);
    var bigClass =  document.getElementById(firstSelObjName);
    var bigClassSelectedIndex = bigClass.selectedIndex;
	var subField= fieldList[bigClassSelectedIndex].subFieldList[selectedIndex];
	var operatorValueList  =  subField.operatorList;
	var compareValueList = subField.valueList;
    fillValueList(selObjName,operatorValueList);
    var valueType = subField.compareValueType;
    
    var row = document.getElementById(rowId);
    
	var cell = row.cells[4];
	
    if(valueType == "true"){
        cell.innerHTML="<select id=compare_value_" + rowNum+" class=smallsel onChange='setSqlToHidden(\"filterTable\")'></select>";
	    fillValueList("compare_value_" + rowNum,compareValueList);
    }else{
       cell.innerHTML="<input type=text size=30 maxlength=512 id=compare_value_" + rowNum + 
			" onBlur='javascript:semicolonValid(\"compare_value_" + rowNum +"\",\"filterTable\")' title=??? class=textnoborder onkeydown='javascript:pressEnter()'>";
    }
    setSqlToHidden("filterTable");
 }
 

 function addField(){
	 fieldList[fieldList.length] = new FieldInfo();
	 return fieldList[fieldList.length - 1];
 }
   

 function addSubField(){
	 sFList[sFList.length] = new SubFieldInfo();
	 return sFList[sFList.length - 1];
 }
   
 function setDefaultTerm(t){
	for(i=0;i<1;i++){
	   insertFilterRow(t);
	}   
  }  
   
   
 
 function insertFilterRow(t){
      var new_num=0;
      var del_id=0;
      tableObj = document.getElementById(t);
      newRow=tableObj.insertRow(tableObj.rows.length);
      if(lastRow%2==0){
         newRow.className="even";
      }else{
         newRow.className="odd";
      }
      lastRow ++;
      new_num=lastRow;
      newRow.id="tdt"+new_num;
      //????????????
      c0=newRow.insertCell(0);
      //c0.className="td2";
      c0.innerText=lastRow;
      //????????????
      c1=newRow.insertCell(1);
      //c1.className="td2";
      c1.innerHTML="<select id=field_name_"+new_num+" class=smallsel title='????????????' " +
	  "onChange='javascript:fillSubFieldToOption(\"sub_field_name_" + new_num+"\",this.selectedIndex);' ></select>";
      //????????????
      c2=newRow.insertCell(2);
      c2.className="td2";
      c2.innerHTML="<select id=sub_field_name_"+new_num+"  class=smallsel title='????????????' " +
	  "onChange='javascript:fillSymbolOption(\"field_name_" +new_num +"\",\"symbol_" +new_num +"\",this.selectedIndex,\"" + newRow.id +
	  "\"," + new_num + ")'></select>"; 
      //?????????
      c3=newRow.insertCell(3);
     // c3.className="td2";
      c3.innerHTML="<select id=symbol_"+new_num+" class=smallsel title='???'></select>";
      //???
      c4=newRow.insertCell(4);
     // c4.className="td2";
      c4.innerHTML="<input type=text size=30 maxlength=512 id=compare_value_" + new_num + " onBlur='javascript:semicolonValid(\"compare_value_" + new_num +"\",\"filterTable\")'  title=? class=textnoborder onkeydown='javascript:pressEnter()'>";
      //????????????
      c5=newRow.insertCell(5);
      //c5.className="td2";
      c5.innerHTML="&nbsp;&nbsp;<input type=button name=button value=X class=b1 onclick=javascript:delTabRow(" + tableObj.id + ",\"tdt"+new_num+"\")>";
      
      fillFieldToOption("field_name_" + new_num);
	  fillSubFieldToOption("sub_field_name_" + new_num,'0');
      fillSymbolOption("field_name_" + new_num,"symbol_"+new_num,'0',newRow.id,new_num);
      setSqlToHidden("filterTable");
    }
    
 
   function fillFieldToOption(selObjName){	
	  var optionObj = null;
	  var selObj = document.getElementById(selObjName);
	  
	  for(var count= 0;count<fieldList.length;count++){
		optionObj = document.createElement("option");
		optionObj.text     = fieldList[count].getName();
		optionObj.value = fieldList[count].getCode();
		selObj.add(optionObj);
 	  }			
   }
   
   
    function fillSubFieldToOption(selObjName,selectedIndex){
    
      var subFieldValue = fieldList[selectedIndex].subFieldList;
	  var optionObj = null;
	  var selObj = document.getElementById(selObjName);
	  while(length!=0){  
         var length=selObj.options.length;
         for(var i=0;i<length;i++)
             selObj.options.remove(i);
         length=length/2;
      }
	  for(var count= 0;count<subFieldValue.length;count++){
		optionObj = document.createElement("option");
		optionObj.text =  subFieldValue[count].getName();
		optionObj.value = subFieldValue[count].getCode();
		selObj.add(optionObj);
 	  }
 	  var new_num = selObjName.substring(selObjName.lastIndexOf("_")+1);
      fillSymbolOption("field_name_" + new_num,"symbol_"+new_num,'0',"tdt"+new_num,new_num);	
      setSqlToHidden('filterTable');
   }
   
  
   function delTabRow(tableObj,rowId){
	  for(var count=0;count < tableObj.rows.length;count++){	
		var rowObj = tableObj.rows[count];		
		if(rowObj.id == rowId){			
			tableObj.deleteRow(count);
			break;
		}
	  }
	  setSqlToHidden("filterTable");
	}
	
	function delAllTabRow(tableObj){
	  for(var count=0;count<=tableObj.rows.length+1;count++){
	      if(tableObj.rows.length !=2) tableObj.deleteRow();
	  }
	}
   
  
   function pressEnter(){
	 if(event.keyCode==13) event.keyCode=9
   }
   
  
   function setDefaultSelectTerm(t){
       for(var i=0;i<1;i++){
          insertFilterRow(t);
       }
   }
   
   //save search rule
   function saveSearchRule(t){
	   var sqlTerm = "";
       tableObj = document.getElementById(t);
       var len = tableObj.rows.length;
       var termTemps = "";
       for(num=1;num<tableObj.rows.length-1;num++){	    
		   var numTemp = tableObj.rows[num+1].cells[0].innerText;
		   termTemps = termTemps + " "+numTemp+" "+",";
           var selObj = document.getElementById("field_name_" + numTemp);
           var subSelObj = document.getElementById("sub_field_name_" + numTemp);
		   var operatorObj = document.getElementById("symbol_"+numTemp);
		   var compareValueObj = document.getElementById("compare_value_"+numTemp);//value
		   var subFieldValue = fieldList[selObj.selectedIndex].subFieldList;
		   var subFieldSelectedIndex = subSelObj.selectedIndex;
		   var operatorSelectedIndex = operatorObj.selectedIndex;
		   var selectedSubFieldObj = subFieldValue[subFieldSelectedIndex];
		   var operator = operatorObj.options[operatorSelectedIndex].text;
		   
		   var compareValue = "";
		   if(compareValueObj.type == "text"){
			  compareValue = compareValueObj.value;
		   }else{
			  var compareSelectedIndex = compareValueObj.selectedIndex;
              compareValue =  compareValueObj[compareSelectedIndex].value;
		   }
		   compareValue = compareValue.replace(/(^\s*)|(\s*$)/g, "");
		   if(operator=="like") compareValue = "%"+compareValue+"%";
		   var term = numTemp +":"+selectedSubFieldObj.getTableName()+"."+selectedSubFieldObj.getColumnName()+" "+operator+" '"+compareValue+"'";
		   if(num != 1){
			   sqlTerm = sqlTerm + ",";
           }
		   sqlTerm = sqlTerm + term;  
	   }
	   var advanceTerm = document.getElementById("$advanceTerm$").value;
	   if(advanceTerm  != ""){
	      checkAdvanceTerm(advanceTerm,termTemps)
	   }
	   sqlTerm = sqlTerm + "$"+advanceTerm;
	   return sqlTerm;
   }
   
  
   function setSqlToHidden(t){
      if(document.getElementsByName("$RadioGroup")[0].checked){
         document.getElementById("$hiddenDefineSql$").value="S1=1$";
      }else{
         document.getElementById("$hiddenDefineSql$").value="S"+saveSearchRule(t);
         //alert(document.getElementById("$hiddenDefineSql$").value="S"+saveSearchRule(t))
      }
   }
   
 
   function clearAdvanceTerm(){
      document.getElementById("$advanceTerm$").value="";
   }
   
   
   function checkAdvanceTerm(str,termTemps){
              var rightPh = 0;
	          var leftPh =0;
	          var termNum="";
	          var temp = "";
			  var flag = false;
			  var errorTerm="";
			  
	          for(i=0;i<str.length;i++){
	               var charStr = str.substring(i,i+1);
		           if(charStr == "("){
		               leftPh++;
		           } 
		          if(charStr == ")"){
		               rightPh++;
		           }
	         	 if(charStr >=0 && charStr<=9){
			           termNum = termNum +charStr;
				
			           if(i==str.length-1){
						      if(termNum.charAt(0) == " "){
					              termNum = termNum.slice(1);
					          }
					        
						     if(termTemps.indexOf(termNum)  == -1){
                                 flag = true;
								 errorTerm = errorTerm + termNum + " ";
							}
			           }
	            }else{
					 if(termNum !=""){
					      if(termTemps.indexOf(termNum)  == -1){
                                 flag = true;
								 errorTerm = errorTerm + termNum + " ";
							}
					 }
					
					 termNum = "";
		        }
	          }
            if(errorTerm != ""){
			   alert("Term "+errorTerm+" is not exist!");
			   return false;
			}
	        if(leftPh != rightPh){
	           alert("please check ( or ) in advance term!!");
			   return false;
	        }
   }
   
 
  function showAdvanceTermDiv(){    
	  //if(document.getElementById("$advanceTermCheckbonx$").checked){
      //   document.getElementById("$termDiv$").style.display=""
	  //}else{
	     document.getElementById("$termDiv$").style.display="none" 
	  //}   
  }
   
 
  function showSelectTerm(){
     document.getElementById("$existTermSelect$").selectedIndex=0;
     if(document.getElementsByName("$RadioGroup")[1].checked){
         document.getElementById("$existTermSelect$").disabled=false;
     }
     if(document.getElementsByName("$RadioGroup")[2].checked){
         var obj = document.getElementById("filterTable");
         delAllTabRow(obj);
         lastRow = 0;
         setDefaultTerm('filterTable');
         document.getElementById("$selectTerm$").style.display="";
	 }else{
	     document.getElementById("$selectTerm$").style.display="none";  
	 } 
  } 
   
  function showExistTerm(data){
       //alert("showExistTerm:"+data);
      var obj = document.getElementById("filterTable");
      if(document.getElementsByName("$RadioGroup")[1].checked){
          if(document.getElementById("$existTermSelect$").selectedIndex!=0){
             document.getElementById("$selectTerm$").style.display="";
             var num = getTermNum(data);
             //delAllTabRow(obj);
          }
      }
      delAllTabRow(obj);
      lastRow = 0;
      //if(document.getElementsByName("$RadioGroup")[0].checked){
         setSqlToHidden("filterTable");
      //}
  } 
  
  
  function getTermNum(data){
      var data1 = new String(data);
      var index = data1.indexOf("$");
      var arr = data1.substring(0,index).split(",");
      var arrLen = arr.length;
      return arrLen;
  }
  
  function semicolonValid(inp,t){
     setSqlToHidden(t);
     var temp = document.getElementById(inp).value
     var mobileReg = new RegExp("(\'|\")+");
     if(mobileReg.test(temp)){
     	 alert("输入框中不能含有 \' 或者 \" ");
        document.getElementById(inp).focus();
     	return;
     }
  }  
  
  
  function parseTerm(data){
      //alert("parseTerm:"+data);
      var data1 = new String(data);
      var index = data1.indexOf("$");
      var advanceTerm ;
      if(index != -1){
          advanceTerm = data1.substring(index+1);
      }
      var arr = data1.substring(0,index).split(",");
      var arrLen = arr.length;
      var obj =  document.getElementById("filterTable");
      var bigClassSelectedIndex;
      var selectedIndex;
    
      for(i=0;i<arrLen;i++){
          var term = new String(arr[i]);
          var termArr =  term.split(":");
          var termNum = termArr[0];
          var new_num=0;
          var del_id=0;
          tableObj = document.getElementById("filterTable");
          newRow=tableObj.insertRow(tableObj.rows.length);
          if(i%2==0){
            newRow.className = 'even';
          }else{
            newRow.className = 'odd';
          }
          lastRow ++;
          new_num=lastRow;
          newRow.id="tdt"+termNum;
          var num = i+2;
          c0=obj.rows[num].cells[0];
          c1=obj.rows[num].cells[1];
          c2=obj.rows[num].cells[2];
          c3=obj.rows[num].cells[3];
          c4=obj.rows[num].cells[4];   
          
          c0=newRow.insertCell(0);
          c0.className="even";
          c0.innerText=termNum;
    
          c1=newRow.insertCell(1);
          c1.className="td2";
          c1.innerHTML="<select id=field_name_"+termNum+" class=smallsel  " +
	      "onChange='javascript:fillSubFieldToOption(\"sub_field_name_" + termNum+"\",this.selectedIndex);' ></select>";
          fillFieldToOption("field_name_" + termNum);
       
     
          c2=newRow.insertCell(2);
          c2.className="even";
          c2.innerHTML="<select id=sub_field_name_"+termNum+"  class=smallsel title='' " +
	      "onChange='javascript:fillSymbolOption(\"field_name_" +termNum +"\",\"symbol_" +termNum +"\",this.selectedIndex,\"" + newRow.id +
	      "\"," + termNum + ")'></select>"; 
      
          c3=newRow.insertCell(3);
          c3.className="even";
          c3.innerHTML="<select id=symbol_"+termNum+" class=smallsel title='???' onchange='setSqlToHidden(\"filterTable\")'></select>";
      
          c4=newRow.insertCell(4);
          c4.className="even";
          c4.innerHTML="<input type=text size=30 maxlength=512 id=compare_value_" + termNum + " onBlur='javascript:semicolonValid(\"compare_value_" + termNum +"\",\"filterTable\")' title=? class=textnoborder onkeydown='javascript:pressEnter()' onKeyUp='setSqlToHidden(\"filterTable\")'>";
     
          c5=newRow.insertCell(5);
          c5.className="even";
          c5.innerHTML="&nbsp;&nbsp;<input type=button name=button value=X class=b1 title=delete onclick=javascript:delTabRow(" + tableObj.id + ",\"tdt"+termNum+"\")>";
      
          
	      fillSubFieldToOption("sub_field_name_" + termNum,'0');
	      
          fillSymbolOption("field_name_" + termNum,"symbol_"+termNum,'0',newRow.id,termNum);
    
         
          var termName = new String(termArr[1]);
          var tableArry = termName.split(".");
          var tableName = tableArry[0];
         
         
          
          var colTemp = new String(tableArry[1]);
          var colArray = colTemp.split(" ");
          var colNameTemp = colArray[0];
          
          
          var phyTemp = new String(colArray[1]);
          var valueT = new String(colArray[2]);
          var valueTempArray = valueT.split("'");
          var valueTemp = valueTempArray[1];
          if(valueTemp.indexOf("%") != -1){
             if(valueTemp.lastIndexOf("%")){
                valueTemp = valueTemp.substring(1,valueTemp.lastIndexOf("%"));
             }
          }
          var maj = obj.rows[num].cells[1].firstChild;//majclass
          var sel = obj.rows[num].cells[2].firstChild;//subclass
          var phy = obj.rows[num].cells[3].firstChild;
          var majLen = maj.length;
          var flag = 0;
          for(n=0;n<majLen;n++){
              var subFieldValue = fieldList[n].subFieldList;
              var sfLen = subFieldValue.length;
              for(f=0;f<sfLen;f++){
                  var selectedSubFieldObj = subFieldValue[f];
                  var tableNameTemp  = selectedSubFieldObj.getTableName();   
                  if(tableName==tableNameTemp){
                     var columnName =  selectedSubFieldObj.getColumnName();    
                     if(columnName==colNameTemp){
                        maj.selectedIndex = n;
                        bigClassSelectedIndex = n;
                        fillSubFieldToOption("sub_field_name_"+termNum,bigClassSelectedIndex);
                        //fillSymbolOption("field_name_" + termNum,"symbol_"+termNum,'0',newRow.id,termNum);
                        flag = 1;
                     }
                  }
                  if(flag==1) break;
              }
              if(flag==1) break;
          }
 			
          var subFieldValue = fieldList[bigClassSelectedIndex].subFieldList;
          // alert()
          for(v=0;v<sel.length;v++){       
              var selectedSubFieldObj = subFieldValue[v];
              var columnName =  selectedSubFieldObj.getColumnName();    
              if(columnName==colNameTemp){
                 sel.selectedIndex = v;
                 selectedIndex = v;
                 //alert("parseTerm:selectedIndex="+selectedIndex+",termNum="+termNum);
                 fillSymbolOption("field_name_" + termNum,"symbol_"+termNum,selectedIndex,newRow.id,termNum);
                // alert("parseTerm:fillSymbolOption end");
             }
          }
          //alert("parseTerm:phy="+phy);
         // alert("parseTerm:optName="+optName);
         // alert("parseTerm:phyTemp="+phyTemp);
         for(x=0;x<phy.length;x++){
             var optName =  phy.options[x].text;
             if(phyTemp==optName){
                 phy.selectedIndex = x;
             }
         }
          
          var subField= fieldList[bigClassSelectedIndex].subFieldList[selectedIndex];
          var valueType = subField.compareValueType;
          var compareValueList = subField.valueList;
          if(valueType == "true"){
              obj.rows[num].cells[4].innerHTML="<select id=compare_value_" + termNum+" class=smallsel onChange='setSqlToHidden(\"filterTable\")'></select>";
	          fillValueList("compare_value_" + termNum,compareValueList);
	          var valueOp = document.getElementById("compare_value_" + termNum);
	          for(m=0;m<valueOp.length;m++){
	              var optValue = valueOp.options[m].value;
	              if(optValue == valueTemp ){
	                 valueOp.selectedIndex = m;
	              }
	          }
	        
          }else{
            obj.rows[num].cells[4].innerHTML="<input type=text size=30 maxlength=512 id=compare_value_" + termNum + 
			" onBlur='javascript:semicolonValid(\"compare_value_" + termNum +"\",\"filterTable\")' class=textnoborder onkeydown='javascript:pressEnter()'>";
			document.getElementById("compare_value_"+termNum).value=valueTemp;
          }
      }
	//document.getElementById("$advanceTermCheckbonx$").checked = true;
	// fillSymbolOption("field_name_" + termNum,"symbol_"+termNum,'0',newRow.id,termNum);
	document.getElementById("$termDiv$").style.display="none";
    document.getElementById("$advanceTerm$").value=advanceTerm;
    document.getElementById("$hiddenDefineSql$").value="S"+saveSearchRule("filterTable");
    //window.document.write(document.body.innerHTML);
  }
  
  
  function reSaveedRule(data){
    showExistTerm(data);  
    parseTerm(data);
  }
  
 
  function saveHiddenDefineSqlBack(data){
      fillSelection1("$existTermSelect$",data);
      var obj = document.getElementById("$existTermSelect$");
      obj.selectedIndex = 1;
      document.getElementsByName("$RadioGroup")[1].checked=true;
      document.getElementById("$existTermSelect$").disabled=false;
      reSaveedRule(document.getElementById("$hiddenDefineSql$").value.substring(1));
  }
  
 function fillSelection1(selectionName,data){
      document.getElementById("$xmlHttpTextField$").value="";
      var v = data[0];
      if(getFrontString(v,",")=="true"){
          alert(getSubString(v,","));
          return false;
      }
      clearSelection(selectionName);
      var models = document.getElementById(selectionName);
      var len = data.length;
      for(var i=1;i<len;i++){
         var value = data[i];
         var optionValue = getFrontString(value,",");
         var optionDisplayName = getSubString(value,",");
         option = document.createElement("option");
         option.text = optionDisplayName;
		 option.value = optionValue;
         models.add(option);
      }
} 
  
  
  /**
 * @author:Ray
 * fill the selection 
 * selectionName: selection id
 * data:data source,data:Array();
 */   
function fillSelection(selectionName,data){
      clearSelection(selectionName);
      var models = document.getElementById(selectionName);
      var len = data.length;
      for(var i=0;i<len;i++){
         var value = data[i];
         var optionValue = getFrontString(value,",");
         var optionDisplayName = getSubString(value,",");
         option = document.createElement("option");
         option.text = optionDisplayName;
		 option.value = optionValue;
         models.add(option);
      }
}
  
function clearSelection(selectionName){
	var models = document.getElementById(selectionName);
      var option = null;
      option = document.createElement("option");
      for(var i=0;i<models.options.length;i++){
      	if(models.options[i].value == ""){
      	    option.text = models.options[i].text;
            option.value = models.options[i].value;
            break;
      	}
      }
	  while(length!=0){  
         var length = models.options.length;
         for(var i=0;i<length;i++){
         		models.options.remove(i);
         }
         length=length/2;
     }
     models.add(option);
}
  
 
  

